﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Icedream.InstantFileTransfer
{
    public class IFTPReply
    {
        internal string _repName;
        internal List<string> _repArgs = new List<string>();
        internal string _repLine;

        public string Name {
            get { return _repName; }
        }
        public string[] Arguments {
            get { return _repArgs.ToArray(); }
        }
        public string Line { get { return _repLine; } }

        internal static IFTPReply ParseLine(string line)
        {
            IFTPReply reply = new IFTPReply();
            reply._repLine = line;
            string[] split1 = line.Split(' ');
            reply._repName = split1[0].ToUpper();
            string[] split2 = string.Join(" ", split1.Skip(1)).Split('"');
            for (double i = 0; i < split2.Length; i++)
            {
                if (i / 2 == Math.Round(i / 2))
                {
                    string[] split3 = split2[(int)i].Split(' ');
                    reply._repArgs.AddRange(split3);
                }
                else
                    reply._repArgs.Add(split2[(int)i]);
            }
            return reply;
        }
    }

    public class IFTPAckReply
    {
        internal IFTPReply reply;

        /// <summary>
        /// Gets the reason, if any
        /// </summary>
        public string Reason { get {
            if (reply.Arguments.Length == 0)
                return "";
            return reply.Arguments.Last();
        } }

        /// <summary>
        /// Gets if the reply is an "ACKnowledged" reply.
        /// </summary>
        public bool IsAcknowledged {
            get
            {
                if (reply._repName == "ACK")
                    return true;
                if (reply._repName == "NACK")
                    return false;
                throw new NotSupportedException("Only reply types ACK and NACK are supported by IFTPAckReply.");
            }
        }

        internal new static IFTPAckReply ParseLine(string line)
        {
            IFTPAckReply ack = new IFTPAckReply();
            ack.reply = IFTPReply.ParseLine(line);
            return ack;
        }
    }
}
